import unittest
import requests
from api.api_register_login import ApiRegisterLogin
from parameterized import parameterized
from util import read_json


class TestRegisterLogin(unittest.TestCase):
    # 初始化
    def setUp(self) -> None:
        self.session = requests.session()
        self.reg = ApiRegisterLogin(self.session)

    # 结束
    def tearDown(self) -> None:
        self.session.close()

    # 注册接口测试
    @parameterized.expand(read_json("register_login.json", "register_test_cases"))
    def test_register(self, username, password, phone, mail, realName, expect_result):  # 修复参数名拼写
        try:
            res = self.reg.api_register(username, password, phone, mail, realName)
            res_json = res.json()  # 解析响应为JSON
            print(res_json)

            if expect_result == "注册成功":
                self.assertTrue(res_json.get("success"),
                                msg=f"正向用例失败，预期success=True，实际返回: {res_json}")
            else:
                self.assertFalse(res_json.get("success"),
                                 msg=f"逆向用例失败，预期success=False，实际返回: {res_json}")
                self.assertIn(expect_result, res_json.get("message", ""),
                                msg=f"错误信息不匹配，预期包含: {expect_result}, 实际返回: {res_json.get('message')}")
        except Exception as e:
            raise

        #登录接口测试

    @parameterized.expand(read_json("register_login.json", "login_test_cases"))
    def test_login(self, username, password, expect_result):
        try:
            res = self.reg.api_login(username, password)
            res_json = res.json()
            print(res_json)
            if expect_result == "登录成功":
                self.assertTrue(res_json.get("success"),
                msg=f"登录成功用例失败，实际返回: {res_json}")
            else:
                self.assertFalse(res_json.get("success"),
                msg=f"登录失败用例断言success错误，实际返回: {res_json}")
                self.assertIn(expect_result, res_json.get("message", ""),
                msg=f"登录错误信息不匹配，预期包含: {expect_result}, 实际: {res_json.get('message')}")
        except Exception as e:
            raise
